package com.tianxin.workbao.workBao.Activity;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.adapter.SelectAddressAdapter;
import com.tianxin.workbao.workBao.adapter.SelectCoalAdapter;
import com.tianxin.workbao.workBao.adapter.SelectCustomerAdapter;
import com.tianxin.workbao.workBao.bean.Address;
import com.tianxin.workbao.workBao.bean.Coal;
import com.tianxin.workbao.workBao.bean.Customers;
import com.tianxin.workbao.workBao.bean.TransContract;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.dataProvide.AddressProvide;
import com.tianxin.workbao.workBao.dataProvide.CoalProvide;
import com.tianxin.workbao.workBao.dataProvide.CustomerProvide;
import com.tianxin.workbao.workBao.dataProvide.TransContractProvide;
import com.tianxin.workbao.workBao.holder.SelectAddressHolder;
import com.tianxin.workbao.workBao.holder.SelectCoalHolder;
import com.tianxin.workbao.workBao.holder.SelectCustomerHolder;
import com.tianxin.workbao.workBao.listener.MyPopupWindowListener;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.SPUtils;
import com.tianxin.workbao.workBao.utils.common.TimeUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by hacker on 2017/7/27.
 */

public class TransContractOptionActivity extends BaseActivity implements View.OnClickListener, UpdateListViewListener, MyPopupWindowListener {

    private TextView numberTv;
    private TextView supplyTv;
    private TextView supplyAddressTv;
    private TextView buyCompanyTv;
    private TextView buyCompanyAddressTv;
    private TextView transCompanyTv;
    private TextView coalTv;
    private RadioButton blurredRb;
    private RadioButton noBlurredRb;
    private EditText inPriceEt;
    private EditText outPriceEt;
    private RadioButton taxRb;
    private RadioButton noTaxRb;
    private EditText taxRateEt;
    private RadioButton sendWeighrRb;
    private RadioButton receivedWeightRb;
    private RadioButton noLossRb;
    private RadioButton lossRb;
    private RadioButton moreThanRb;
    private EditText lossValueEt;
    private EditText lossPriceEt;
    private TextView startTimeEt;
    private EditText remarkEt;
    private FloatingActionButton saveFab;
    private String contractNumber;
    private TransContract mTransContract;
    private int companyType;

    private CoalProvide coalProvide;
    private CustomerProvide customerProvide;
    private AddressProvide addressProvide;
    private TransContractProvide transContractProvide;
    private List<Coal> mCoalList;
    private List<Customers> mCustomerList;
    private List<Address> mAddressList;
    private PopupWindow popupWindow;

    private com.jzxiang.pickerview.TimePickerDialog mTimePickerDialog;
    private final int POPUP_TYPE_COAL = 0;
    private final int POPUP_TYPE_CUSTOMER = 1;
    private final int POPUP_TYPE_ADDRESS = 2;
    private int addressType = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.trans_contract_option);

        initView();
        initData();
        initEvent();
        bindView();
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("运输合同录入");
        mToolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_action_back_24dp));
        setSupportActionBar(mToolbar);
        saveFab = (FloatingActionButton) findViewById(R.id.save_fab);
        numberTv = (TextView) findViewById(R.id.number);
        supplyTv = (TextView) findViewById(R.id.supply);
        supplyAddressTv = (TextView) findViewById(R.id.supply_address);
        buyCompanyTv = (TextView) findViewById(R.id.buy_company);
        buyCompanyAddressTv = (TextView) findViewById(R.id.buy_company_address);
        transCompanyTv = (TextView) findViewById(R.id.trans_company);
        coalTv = (TextView) findViewById(R.id.coal);
        blurredRb = (RadioButton) findViewById(R.id.blurred);
        noBlurredRb = (RadioButton) findViewById(R.id.no_blurred);
        inPriceEt = (EditText) findViewById(R.id.in_price);
        outPriceEt = (EditText) findViewById(R.id.out_price);
        taxRb = (RadioButton) findViewById(R.id.tax);
        noTaxRb = (RadioButton) findViewById(R.id.no_tax);
        taxRateEt = (EditText) findViewById(R.id.tax_rate);
        sendWeighrRb = (RadioButton) findViewById(R.id.send_weight);
        receivedWeightRb = (RadioButton) findViewById(R.id.received_weight);
        noLossRb = (RadioButton) findViewById(R.id.no_loss);
        lossRb = (RadioButton) findViewById(R.id.loss);
        moreThanRb = (RadioButton) findViewById(R.id.more_than);
        lossValueEt = (EditText) findViewById(R.id.loss_value);
        lossPriceEt = (EditText) findViewById(R.id.loss_price);
        remarkEt = (EditText) findViewById(R.id.remark);
        startTimeEt = (TextView) findViewById(R.id.start_time);
    }

    @Override
    public void initData() {
        contractNumber = BeansUtil.getNumber(Constant.TRANS_CONTRACT_HEADER);
        mTransContract = new TransContract();
        mTransContract.setTctnum(contractNumber);
        mTransContract.setAdduserid((int) SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0));
        mTransContract.setAddusername(SPUtils.getPrefString(Constant.CURRENT_USER_NAME, "no"));
        mTransContract.setStatus(0);
    }


    @Override
    public void initEvent() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TransContractOptionActivity.this.finish();
            }
        });
        saveFab.setOnClickListener(this);
        supplyTv.setOnClickListener(this);
        supplyAddressTv.setOnClickListener(this);
        buyCompanyTv.setOnClickListener(this);
        buyCompanyAddressTv.setOnClickListener(this);
        transCompanyTv.setOnClickListener(this);
        coalTv.setOnClickListener(this);
        blurredRb.setOnClickListener(this);
        noBlurredRb.setOnClickListener(this);
        taxRb.setOnClickListener(this);
        noTaxRb.setOnClickListener(this);
        sendWeighrRb.setOnClickListener(this);
        receivedWeightRb.setOnClickListener(this);
        noLossRb.setOnClickListener(this);
        lossRb.setOnClickListener(this);
        moreThanRb.setOnClickListener(this);
        startTimeEt.setOnClickListener(this);

    }

    @Override
    public void bindView() {
        numberTv.setText(contractNumber);
    }

    //View.OnClickListener
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //save sampling to server and local db
            case R.id.save_fab:
                save();
                break;
            //select coals
            case R.id.coal:
                getCoalList();
                break;
            //select supply
            case R.id.supply:
                this.companyType = Constant.CUSTOMER_TYPE_SALE;
                getCustomerList();
                break;
            //select supply address
            case R.id.supply_address:
                addressType = 1;
                getAddressList();
                break;
            //select buy
            case R.id.buy_company:
                this.companyType = Constant.CUSTOMER_TYPE_BUY;
                getCustomerList();
                break;
            //select buy address
            case R.id.buy_company_address:
                addressType = 2;
                getAddressList();
                break;
            //select buy address
            case R.id.trans_company:
                this.companyType = Constant.CUSTOMER_TYPE_TRANS;
                getCustomerList();
                break;
            //blurred
            case R.id.no_blurred:
                if (noBlurredRb.isChecked() == true) {
                    mTransContract.setIsblurred(0);
                    inPriceEt.setVisibility(View.GONE);
                } else {
                    inPriceEt.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.blurred:
                if (blurredRb.isChecked() == true) {
                    mTransContract.setIsblurred(1);
                    inPriceEt.setVisibility(View.VISIBLE);
                } else {
                    inPriceEt.setVisibility(View.GONE);
                }
                break;
            //pay type
            case R.id.send_weight:
                if (sendWeighrRb.isChecked()) {
                    mTransContract.setTranspaytype(2);
                }
                break;
            case R.id.received_weight:
                if (receivedWeightRb.isChecked()) {
                    mTransContract.setTranspaytype(1);
                }
                break;
            //tax
            case R.id.tax:
                if (taxRb.isChecked()) {
                    mTransContract.setIsaddtax(1);
                    taxRateEt.setVisibility(View.GONE);
                } else {
                    taxRateEt.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.no_tax:
                if (noTaxRb.isChecked()) {
                    mTransContract.setIsaddtax(0);
                    taxRateEt.setVisibility(View.VISIBLE);
                } else {
                    taxRateEt.setVisibility(View.GONE);
                }
                break;
            //loss type
            case R.id.no_loss:
                if (noLossRb.isChecked()) {
                    mTransContract.setLosstype(1);
                }
                break;
            case R.id.loss:
                if (lossRb.isChecked()) {
                    mTransContract.setLosstype(2);
                }
                break;
            case R.id.more_than:
                if (moreThanRb.isChecked()) {
                    mTransContract.setLosstype(3);
                }
            case R.id.start_time:
                getTimePickerDialog(new OnDateSetListener() {
                    @Override
                    public void onDateSet(com.jzxiang.pickerview.TimePickerDialog timePickerView, long millseconds) {
                        startTimeEt.setText(TimeUtils.parseDateTime(new Date(millseconds)));
                    }
                }).show(getSupportFragmentManager(), "all");
                break;
        }
    }

    /**
     * save the sampling
     */
    private void save() {
        if (mTransContract == null) {
            showMessage("数据异常");
            return;
        }
        mTransContract.setAddtime(new Date());
        // check
        if (mTransContract.getSendcompanyid() == null || mTransContract.getSendcompanyid() < 1) {
            showMessage("请选择发货公司");
            return;
        }
        if (mTransContract.getSendaddressid() == null || mTransContract.getSendaddressid() < 1) {
            showMessage("请选择发货公司地址");
            return;
        }
        if (mTransContract.getReceivecompanyid() == null || mTransContract.getReceivecompanyid() < 1) {
            showMessage("请选择收货公司");
            return;
        }
        if (mTransContract.getReciveaddressid() == null || mTransContract.getReciveaddressid() < 1) {
            showMessage("请选择收货公司地址");
            return;
        }
        if (mTransContract.getReceivecompanyid() == null || mTransContract.getTranscompanyid() < 1) {
            showMessage("请选择运输公司");
            return;
        }
        if (mTransContract.getCoaltypeid() == null || mTransContract.getCoaltypeid() < 1) {
            showMessage("请选择煤种");
            return;
        }
        if (noBlurredRb.isChecked()) {
            mTransContract.setIsblurred(0);
        }
        if (blurredRb.isChecked()) {
            mTransContract.setIsblurred(1);
        }
        if (mTransContract.getIsblurred() == null) {
            showMessage("请选择是否区分内外价格");
            return;
        }
        try {
            mTransContract.setTransunitprice(Float.valueOf(outPriceEt.getText().toString()));
        } catch (NumberFormatException e) {
            showMessage("输入价格格式不正确");
            return;
        }

        if (mTransContract.getTransunitprice() == null || mTransContract.getTransunitprice() < 0) {
            showMessage("请输入价格");
            return;
        }
        if (mTransContract.getIsblurred() == 1) {

            try {
                mTransContract.setIntransunitprice(Float.valueOf(inPriceEt.getText().toString()));
            } catch (NumberFormatException e) {
                showMessage("输入价格格式不正确");
                return;
            }
            if (mTransContract.getIntransunitprice() == null || mTransContract.getIntransunitprice() < 0) {
                showMessage("请输入内部价格");
                return;
            }
        }
        if (noTaxRb.isChecked()) {
            mTransContract.setIsaddtax(0);
        }
        if (taxRb.isChecked()) {
            mTransContract.setIsaddtax(1);
        }
        if (mTransContract.getIsaddtax() == null) {
            showMessage("请选择是否含税");
            return;
        }
        if (mTransContract.getIsaddtax() == 0) {
            try {
                mTransContract.setTaxrate(Float.valueOf(taxRateEt.getText().toString()));
            } catch (NumberFormatException e) {
                showMessage("输入税率格式不正确");
                return;
            }
            if (mTransContract.getTaxrate() == null || mTransContract.getTaxrate() < 0) {
                showMessage("请选输入税率");
                return;
            }
        }
        if (sendWeighrRb.isChecked()) {
            mTransContract.setTranspaytype(2);
        }
        if (receivedWeightRb.isChecked()) {
            mTransContract.setTranspaytype(1);
        }
        if (mTransContract.getTranspaytype() == null) {
            showMessage("请选择结算依据");
            return;
        }
        if (noLossRb.isChecked()) {
            mTransContract.setLosstype(1);
        }
        if (lossRb.isChecked()) {
            mTransContract.setLosstype(2);
        }
        if (moreThanRb.isChecked()) {
            mTransContract.setLosstype(3);
        }
        if (mTransContract.getLosstype() == null) {
            showMessage("请选择路耗类型");
            return;
        }

        if (mTransContract.getLosstype() != 1) {
            try {
                mTransContract.setLossvalue(Float.valueOf(lossValueEt.getText().toString()));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            if (mTransContract.getLossvalue() == null || mTransContract.getLossvalue() < 0) {
                showMessage("请选输入合理路耗");
                return;
            }
            try {
                mTransContract.setOutlossunitprice(Float.valueOf(lossPriceEt.getText().toString()));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (mTransContract.getOutlossunitprice() == null || mTransContract.getOutlossunitprice() < 0) {
                showMessage("请选输超损扣价");
                return;
            }
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                mTransContract.setTransstarttime(sdf.parse(startTimeEt.getText().toString()));
            } catch (ParseException e) {
                showMessage("请输入生效时间格式错误");
                return;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if (mTransContract.getTransstarttime() == null) {
            showMessage("请输入生效时间");
            return;
        }
        //save
        getTransContractProvide().save(mTransContract);
    }

    private void getCoalList() {
        getCoalProvide().getAllCoals();
    }


    private void getCustomerList() {
        getCustomerProvide().getAllCustomers(companyType);
    }

    private void getAddressList() {
        if (addressType == 1) {
            if (mTransContract.getSendcompanyid() != null) {
                getAddressProvide().getdatas(mTransContract.getSendcompanyid(), 1);
            } else {
                showMessage("请先选择发货公司");
                return;
            }
        } else {
            if (mTransContract.getReceivecompanyid() != null) {
                getAddressProvide().getdatas(mTransContract.getReceivecompanyid(), 1);
            } else {
                showMessage("请先选择收货公司");
                return;
            }
        }

    }

    @Override
    public void OnMyClick(Integer selectType, Integer id, String information) {

        switch (selectType) {
            case Constant.SELECT_TYPE_COAL:
                dismissPoPup();
                mTransContract.setCoaltypename(information);
                mTransContract.setCoaltypeid(id);
                coalTv.setText(information);
                break;
            case Constant.SELECT_TYPE_CUSTOMER:
                dismissPoPup();
                if (companyType == Constant.CUSTOMER_TYPE_BUY) {
                    mTransContract.setReceivecompanyid(id);
                    mTransContract.setReceivecompanyname(information);
                    buyCompanyTv.setText(information);
                } else if (companyType == Constant.CUSTOMER_TYPE_SALE) {
                    mTransContract.setSendcompanyid(id);
                    mTransContract.setSendcompanyname(information);
                    supplyTv.setText(information);
                } else if (companyType == Constant.CUSTOMER_TYPE_TRANS) {
                    mTransContract.setTranscompanyid(id);
                    mTransContract.setTranscompany(information);
                    transCompanyTv.setText(information);
                }
                break;
            case Constant.SELECT_TYPE_ADDRESS:
                dismissPoPup();
                if (companyType == Constant.CUSTOMER_TYPE_SALE) {
                    mTransContract.setReciveaddressid(id);
                    mTransContract.setReciveaddress(information);
                    supplyAddressTv.setText(information);
                } else {
                    mTransContract.setSendaddressid(id);
                    mTransContract.setSendaddress(information);
                    buyCompanyAddressTv.setText(information);
                }
                break;
        }
    }

    @Override
    public void showMessage(String msg) {
        if (msg == "ok") {
            this.finish();
        } else if (msg.contains("failure")) {
            Toast.makeText(this, "录入失败！\n " + msg.substring(msg.indexOf("failure") + 1, msg.length()), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void showProgress() {
        getSweetAlertDialog(this).showDialog("", 2000);
    }

    @Override
    public void hideProgress() {
        getSweetAlertDialog(this).dismiss();
    }

    @Override
    public void onRefreshData(Object result) {
        if (result instanceof List) {
            if (((List) result).size() > 0) {
                if (((List) result).get(0) instanceof Coal) {
                    mCoalList = (List<Coal>) result;
                    if (mCoalList.size() > 0) {
                        showSelectPopup(POPUP_TYPE_COAL);
                    }
                } else if (((List) result).get(0) instanceof Customers) {
                    mCustomerList = (List<Customers>) result;
                    if (mCustomerList.size() > 0) {
                        showSelectPopup(POPUP_TYPE_CUSTOMER);
                    }
                } else if (((List) result).get(0) instanceof Address) {
                    mAddressList = (List<Address>) result;
                    if (mAddressList.size() > 0) {
                        showSelectPopup(POPUP_TYPE_ADDRESS);
                    }
                }
            }
        } else {
            showMessage("response other information");
        }
    }

    private void showSelectPopup(int type) {
        popupWindow = new PopupWindow();
        switch (type) {
            case POPUP_TYPE_COAL:
                SelectCoalAdapter selectCoalAdapter = new SelectCoalAdapter(mCoalList, this, this);
                SelectCoalHolder selectCoalHolder = new SelectCoalHolder(this, this, selectCoalAdapter);
                popupWindow.setContentView(selectCoalHolder.getContentView());
                popupWindow.setHeight(340);
                break;
            case POPUP_TYPE_CUSTOMER:
                SelectCustomerAdapter selectCustomerAdapter = new SelectCustomerAdapter(mCustomerList, this, this);
                SelectCustomerHolder selectCustomerHolder = new SelectCustomerHolder(this, this, selectCustomerAdapter);
                popupWindow.setContentView(selectCustomerHolder.getContentView());
                popupWindow.setHeight(400);
                break;
            case POPUP_TYPE_ADDRESS:
                SelectAddressAdapter selectAddressAdapter = new SelectAddressAdapter(mAddressList, this, this);
                SelectAddressHolder selectAddressHolder = new SelectAddressHolder(this, this, selectAddressAdapter);
                popupWindow.setContentView(selectAddressHolder.getContentView());
                popupWindow.setHeight(300);
                break;
            default:
                return;
        }
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.write)));
        popupWindow.setAnimationStyle(R.style.my_popup_animation_style);
        popupWindow.showAtLocation(mToolbar, Gravity.TOP, 0, 0);
    }

    @Override
    public void onLoadMoreData(Object result) {

    }

    public CoalProvide getCoalProvide() {
        if (coalProvide == null) {
            coalProvide = new CoalProvide(this, this);
        }
        return coalProvide;
    }

    public CustomerProvide getCustomerProvide() {
        customerProvide = new CustomerProvide(this, this, this.companyType);
        return customerProvide;
    }

    public AddressProvide getAddressProvide() {
        addressProvide = new AddressProvide(this, this);
        return addressProvide;
    }

    public TransContractProvide getTransContractProvide() {
        if (transContractProvide == null) {
            transContractProvide = new TransContractProvide(this, this);
        }
        return transContractProvide;
    }

    private void dismissPoPup() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

}
